package demo.vo.tsdb;


import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

public class XdcsCouter {
    // 指标值
    private final ConcurrentMap<List<String>, AtomicLong> childrenValue;
    // 指标名称
    private String name;
    // 指标描述
    private String desc;
    // 标签名称
    private List<String> labelNames;

    public XdcsCouter(String name, String desc, String... labelNames) {
        this.name = name;
        this.desc = desc;
        if (labelNames.length == 0) {
            this.labelNames = Collections.emptyList();
        } else {
            this.labelNames = Arrays.asList(labelNames);
        }
        this.childrenValue = new ConcurrentHashMap<>();
    }


    /**
     * 增加值
     *
     * @param delta
     * @param labelValues
     */
    public long inc(long delta, String... labelValues) {
        if (labelValues.length != labelNames.size()) {
            throw new IllegalArgumentException("Incorrect number of labels.");
        }
        for (String label : labelValues) {
            if (label == null) {
                throw new IllegalArgumentException("Label cannot be null.");
            }
        }
        List<String> key = Arrays.asList(labelValues);
        AtomicLong c = childrenValue.get(key);
        if (c == null) {
            AtomicLong c2 = new AtomicLong();
            AtomicLong tmp = childrenValue.putIfAbsent(key, c2);
            c = (tmp == null) ? c2 : tmp;
        }
        return c.addAndGet(delta);
    }


}
